package com.itcast.flink.connectors.kafka;

import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.streaming.connectors.kafka.internals.KeyedSerializationSchemaWrapper;

import java.util.Properties;

/**
 * <p>Description: </p>
 *
 * @author
 * @version 1.0
 * <p>Copyright:Copyright(c)2020</p>
 * @date
 */
public class KafkaSinkApplication {
    
    public static void main(String[] args) throws Exception {
        
        // 1. 创建运行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        
        // 2. 读取Socket数据源
        DataStreamSource<String> socketStr = env.socketTextStream("192.168.23.128", 9911, "\n");
        
        // 3. Kakfa的生产者配置
      /*  FlinkKafkaProducer kafkaProducer = new FlinkKafkaProducer(
                "192.168.23.140:9092",            // broker 列表
                "flink-topic",                  // 目标 topic
                new SimpleStringSchema());   // 序列化 方式*/
        
        Properties prop = new Properties();
        prop.setProperty("bootstrap.servers", "192.168.23.140:9092");
        FlinkKafkaProducer kafkaProducer = new FlinkKafkaProducer(
                "flink-topic",
                new KeyedSerializationSchemaWrapper(new SimpleStringSchema()),
                prop,
                FlinkKafkaProducer.Semantic.AT_LEAST_ONCE);
        kafkaProducer.setWriteTimestampToKafka(true);
        
        // 4. 添加kafka的写入器
        socketStr.addSink(kafkaProducer);
        socketStr.print().setParallelism(1);
        
        // 5. 执行任务
        env.execute("job");
    }
}
